package com.tuxing.draa_data.util.easyExcel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.tuxing.draa_data.dto.EjJcrJournalExcelDto;
import com.tuxing.draa_data.service.subject.SubjectService;

import java.util.List;

/**
 * @author yuanshihang
 * @version 1.0
 * @className EjEiJournalDataListener
 * @description 基础描述: EI核心数据解析
 * @date 2022/2/14 10:36
 */
public class EjEiJournalDataListener implements ReadListener<EjJcrJournalExcelDto> {

    private SubjectService subjectService;

    public EjEiJournalDataListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    /**
     * 每隔1000条存储数据库，实际使用中可以1000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;

    /**
     * 缓存的数据
     */
    private List<EjJcrJournalExcelDto> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);


    @Override
    public void invoke(EjJcrJournalExcelDto ejJcrJournalExcelDto, AnalysisContext analysisContext) {
//        log.info("解析到一条数据:{}", JSON.toJSON(draaExcelDto));
        cachedDataList.add(ejJcrJournalExcelDto);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        subjectService.jcrJournalParse(cachedDataList);
    }
}
